package com.fjnu.controller;

import com.fjnu.dao.TagDao;
import com.fjnu.dto.ResponseResult;
import com.fjnu.entity.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/blog-api/v0.1/tag")
public class TagController {

    @Autowired
    private TagDao tagDao;

    /**
     * 罗列所有的标签
     */
    @GetMapping("/list")
    public ResponseResult<List<Tag>> list() {
        try {
            List<Tag> tags = tagDao.selectAll();
            return ResponseResult.success(tags);
        } catch (Exception e) {
            return ResponseResult.error("查询标签列表失败: " + e.getMessage());
        }
    }

    /**
     * 新增标签
     */
    @PostMapping("/add")
    public ResponseResult add(@RequestBody Tag tag) {
        try {
            int result = tagDao.insert(tag);
            if (result > 0) {
                return ResponseResult.success(null);
            } else {
                return ResponseResult.error("新增标签失败");
            }
        } catch (Exception e) {
            return ResponseResult.error("新增标签异常: " + e.getMessage());
        }
    }

    /**
     * 删除指定标签
     */
    @GetMapping("/delete")
    public ResponseResult delete(@RequestParam String tagId) {
        try {
            Integer id = Integer.parseInt(tagId);
            int result = tagDao.delete(id);
            if (result > 0) {
                return ResponseResult.success(null);
            } else {
                return ResponseResult.error("删除标签失败");
            }
        } catch (NumberFormatException e) {
            return ResponseResult.error("标签ID格式错误");
        } catch (Exception e) {
            return ResponseResult.error("删除标签异常: " + e.getMessage());
        }
    }
}